package com.dahua.messagesyncbj.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.core.KafkaAdmin;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class KafkaConfig {
    private AdminClient adminClient;

    @Bean
    public AdminClient adminClient(KafkaAdmin kafkaAdmin) {
        log.info(kafkaAdmin.getConfigurationProperties().toString());
        adminClient = AdminClient.create(kafkaAdmin.getConfigurationProperties());
        return adminClient;
    }

    public void adminClose() {
        adminClient.close();
    }

    @Bean
    public KafkaListenerContainerFactory<?> batchConsumerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
        //需要改配置
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "default_group");
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        //最大批量消费
        props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 4000);
        //自动确认off
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 180000);
        //consumer等待请求响应的最大时间
        props.put(ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, 30000);
        //心跳
        props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG,60000);
        //序列
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

        factory.setConsumerFactory(new DefaultKafkaConsumerFactory<>(props));
        //<=分区数目
        factory.setConcurrency(1);
        factory.getContainerProperties().setPollTimeout(1500);
        factory.setBatchListener(true);
        factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
        return factory;
    }

}
